/************************************************************************
Copyright 2003, 2004, 2005, 2006, 2007, 2008 Grid Technology Research Center,
National Institute of Advanced Industrial Science and Technology.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
************************************************************************/

package jp.aist.gtrc.plus.scheduler.node;

import java.util.Collection;
import java.util.LinkedList;

import jp.aist.gtrc.plus.scheduler.status.NodeStatus;
import jp.aist.gtrc.plus.scheduler.util.CollectionUtil;


public class NodeManager {

	private final NodeInfoMap nodeMap;

	public NodeManager() {

		nodeMap = new NodeInfoMap();

	}

	public synchronized void update(Collection<NodeStatus> nodes){

		if (CollectionUtil.isEmpty(nodes))
			return;

		for (NodeStatus node : nodes) {
			addNode(node);
		}

		/*
		 * NOTE: Don't call nodeMap.clear() here.
		 * NodeInfo has its reserve information.
		 */
		Collection<NodeInfo> infos =
			new LinkedList<NodeInfo>(nodeMap.getNodes());
		for (NodeInfo info : infos) {
			NodeStatus status = info.getStatus();
			if (nodes.contains(status) == false) {
				nodeMap.remove(info);
			}
		}

	}

	public synchronized void addNode(NodeStatus node) {

		assert(node != null);

		NodeInfo info = nodeMap.get(node.getName());
		if (info == null) {
			nodeMap.addNode(node);
		} else {
			info.update(node);
		}

	}

	public synchronized Collection<NodeInfo> getNodes(){

		return nodeMap.getNodes();

	}

	public synchronized int getNodeNum() {

		return nodeMap.size();

	}

	public synchronized NodeInfo getNode(String nodeName) {

		return nodeMap.get(nodeName);

	}

	public synchronized Collection<NodeInfo> getUnreservedNodes() {

		LinkedList<NodeInfo> unrsv = new LinkedList<NodeInfo>();

		for (NodeInfo node : getNodes()) {
			if (node.isReservedNow() == false)
				unrsv.add(node);
		}

		return unrsv;

	}

	public synchronized void changeNodeInfoPair(NodeInfo infoA,
			NodeInfo infoB) {

		nodeMap.changeNodeInfoPair(infoA, infoB);

	}

}
